import { fetchHotSongs, fetchBanners, type Song, getAllSongs } from '../../utils/api';
import { toggleFavorite as toggleFav, getFavorites, setPlaylist } from '../../utils/storage';
import { getAudio, playSong, pause, getState } from '../../utils/audio';

Component({
  data: {
    banners: [] as any[],
    songs: [] as Song[],
    favIds: new Set<string>(),
    currentSong: null as Song | null,
    paused: true
  },
  lifetimes: {
    async attached() {
      const [banners, songs] = await Promise.all([fetchBanners(), fetchHotSongs()]);
      const fav = getFavorites();
      const favIds = new Set(fav.map(s => s.id));
      const songsWithLike = songs.map(s => ({ ...s, liked: favIds.has(s.id) }));
      this.setData({ banners, songs: songsWithLike, favIds });
      setPlaylist(songs);
      
      // 监听音频状态变化
      const a = getAudio();
      a.offTimeUpdate();
      a.onTimeUpdate(() => {
        const state = getState();
        this.setData({ 
          currentSong: state.currentSong,
          paused: state.paused 
        });
      });
    }
  },
  methods: {
    onPlaySong(e: any) {
      const song: Song = e.detail.song;
      playSong(song, () => this.onMiniNext());
      this.setData({ currentSong: song, paused: false });
      // 播放后跳转到播放界面
      wx.navigateTo({ url: `/pages/player/index?id=${song.id}` });
    },
    onToggleLike(e: any) {
      const song: Song = e.detail.song;
      const nextFav = toggleFav(song);
      const favIds = new Set(nextFav.map(s => s.id));
      const songs = this.data.songs.map(s => ({ ...s, liked: favIds.has(s.id) }));
      this.setData({ favIds, songs });
    },
    
    onMiniPlayPause() {
      if (this.data.paused) {
        if (this.data.currentSong) {
          playSong(this.data.currentSong, () => this.onMiniNext());
        }
      } else {
        pause();
      }
      this.setData({ paused: !this.data.paused });
    },
    
    onMiniNext() {
      const list = getAllSongs();
      const currentSong = this.data.currentSong;
      if (!currentSong) return;
      
      const currentIndex = list.findIndex(song => song.id === currentSong.id);
      const nextIndex = (currentIndex + 1) % list.length;
      const nextSong = list[nextIndex];
      
      playSong(nextSong, () => this.onMiniNext());
      this.setData({ currentSong: nextSong, paused: false });
    },
    
    onMiniPrev() {
      // 上一首功能需要额外的实现，这里暂时留空
    },
    
    onMiniPlayerTap() {
      if (this.data.currentSong) {
        wx.navigateTo({ url: `/pages/player/index?id=${this.data.currentSong.id}` });
      }
    }
  }
});